package com.horoscope.astrology.zodiac.signs.free.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.*
import androidx.core.content.ContextCompat
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.activity.PreMainActivity
import com.horoscope.astrology.zodiac.signs.free.bean.CityInfo
import com.horoscope.astrology.zodiac.signs.free.utils.ConstellationUtil
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.SysUtils
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectCity
import com.horoscope.astrology.zodiac.signs.free.view.CustomDatePicker
import java.util.*


/**
 *  出生年月（这里会内部改变一次）
 * */
class BirthdayFragment : BaseFragment(), View.OnClickListener {

    private var mDatePick: CustomDatePicker? = null
    private var mStar: ImageView? = null
    private var mContinue: TextView? = null
    private var mBirthReply: TextView? = null
    private var mReplyLinear: LinearLayout? = null
    private var mGuideContent: TextView? = null
    private var mBornPlace: EditText? = null
    private var mEnter: ImageView? = null
    private var birthday = ""

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_birthday, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        initPicker()
        setGuideContent(mGuideContent, "Your name", getString(R.string.tips_birthday_tip))

    }

    private fun initView(view: View) {
        mDatePick = view.findViewById(R.id.date_picker)
        mStar = view.findViewById(R.id.image_view_star)
        mContinue = view.findViewById(R.id.text_view_continue)
        mBirthReply = view.findViewById(R.id.text_view_reply_birthday)
        mReplyLinear = view.findViewById(R.id.linear_layout_reply_birthday)
        mGuideContent = view.findViewById(R.id.text_view_content_birthday)
        mRoot = view.findViewById(R.id.linear_root_birthday)

        mEnter?.setOnClickListener(this)
        mContinue?.setOnClickListener(this)
        mDatePick!!.setPickerMargin(0)
        mDatePick!!.setDividerColor(ContextCompat.getColor(activity, R.color.transparent))
        mDatePick!!.maxDate = System.currentTimeMillis()
        mBornPlace?.setOnClickListener {
            val dialog = DialogSelectCity(null)
            dialog.show(childFragmentManager, "gg")
            dialog.setClickListener(object : DialogSelectCity.ICityOnClick {
                override fun onCityClick(bean: CityInfo) {
                    mBornPlace?.setText(StringBuilder("${bean.name}, ${bean.adminName1}, \n${bean.countryName}"))
                    if (activity is PreMainActivity && isAdded) {
                        (activity as PreMainActivity).setCityInfo(bean)
                    }
                }
            })
        }
        setName("Your name")
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.text_view_continue -> {
                val anim = AnimationUtils.loadAnimation(activity, R.anim.fade_out)
                mDatePick?.startAnimation(anim)
                mContinue?.startAnimation(anim)
                anim.setAnimationListener(object : Animation.AnimationListener {
                    override fun onAnimationRepeat(animation: Animation?) {
                    }

                    override fun onAnimationEnd(animation: Animation?) {
                        showReply()
                        mContinue!!.clearAnimation()
                        mContinue!!.visibility = View.INVISIBLE
                    }

                    override fun onAnimationStart(animation: Animation?) {
                    }

                })
            }
        }
    }


    private fun fadeOutRoot() {
//        hideInput()
        val anim = AnimationUtils.loadAnimation(activity, R.anim.fade_out)
        mRoot?.startAnimation(anim)
        anim.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                if (activity is PreMainActivity) {
                    (activity as PreMainActivity).setPage(1)
                }
            }

            override fun onAnimationStart(animation: Animation?) {
            }

        })
    }

    private fun showReply() {
        var dayStr = mDay.toString()
        var monthStr = mMonth.toString()
        if (mDay!! < 10) {
            dayStr = "0$dayStr"
        }
        if (mMonth!! < 10) {
            monthStr = "0$mMonth"
        }
        mBirthReply?.text = StringBuilder("$monthStr-$dayStr-$mYear")
        // 选择了某个生日，只打一次
        FlurryEventUtil.putDataToEvent(
            EventType.TYPE_SPLASH_BIRTHDAY,
            "type",
            "$mYear-$monthStr-$dayStr"
        )
        (activity as PreMainActivity).setBirthday("$monthStr-$dayStr-$mYear")
        val fadeIn = AnimationUtils.loadAnimation(activity, R.anim.fade_in)
        mReplyLinear?.visibility = View.VISIBLE
        mReplyLinear?.startAnimation(fadeIn)
        fadeIn.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationRepeat(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                mDatePick?.postDelayed({
                    fadeOutRoot()
                }, 200)

            }

            override fun onAnimationStart(animation: Animation?) {
            }

        })
    }

    private var mMonth: Int? = null
    private var mDay: Int? = null
    private var mYear: Int? = null


    private fun initPicker() {
        //
        val calendar = Calendar.getInstance(Locale.ENGLISH)
        val yearNow = calendar.get(Calendar.YEAR) - 18
        val monthNow = calendar.get(Calendar.MONTH) + 1
        val dayNow = calendar.get(Calendar.DAY_OF_MONTH)
        //val week = calendar.get(Calendar.DAY_OF_WEEK)

        mDatePick?.descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
        //初始化datePicker----每次改变日期监听
        mDatePick?.init( // DatePick 月份是0-11 故-1
            yearNow, monthNow - 1, dayNow
        ) { _, year, monthOfYear, dayOfMonth ->
            // 这里的月份是当前月-1
            mStar?.setImageDrawable(
                resources.getDrawable(
                    ConstellationUtil.getConstellationDrawable(
                        monthOfYear,
                        dayOfMonth,
                        1
                    ), null
                )
            )
            (activity as PreMainActivity).setConstellationName(
                ConstellationUtil.getConstellationName(
                    monthOfYear,
                    dayOfMonth
                )
            )
            mYear = year
            mMonth = monthOfYear + 1
            mDay = dayOfMonth
            birthday = "$mMonth-$mDay-$mYear"
        }

        mYear = yearNow
        mMonth = monthNow
        mDay = dayNow

        //设置最大日期
        val g = GregorianCalendar(yearNow + 18, monthNow, dayNow)
        mDatePick?.maxDate = g.timeInMillis
        mStar?.setImageDrawable(
            resources.getDrawable(
                ConstellationUtil.getConstellationDrawable(monthNow - 1, dayNow, 1), null
            )
        )
        (activity as PreMainActivity).setConstellationName(
            ConstellationUtil.getConstellationName(
                monthNow - 1,
                dayNow
            )
        )
    }

    private var mName = ""

    @SuppressLint("SetTextI18n")
    fun setName(name: String) {
        if (isAdded)
            mName = name
        setGuideContent(mGuideContent, "Stranger", getString(R.string.tips_birthday_tip))
    }

    private fun setGuideContent(textView: TextView?, name: String, str: String) {
        if (!SysUtils.isContainChinese(mName)) {
            textView?.text = StringBuilder("Stranger! $str")
        } else {
            val byteSize = name.toByteArray().size
            val newByte = ByteArray(18)
            if (byteSize > 18) {
                for (i in 0..17) {
                    newByte[i] = name.toByteArray()[i]
                }
                textView?.text = StringBuilder(String(newByte) + "...! " + str)
            } else {
                textView?.text = StringBuilder("$name! $str")
            }
        }
    }

}
